package com.deer.backup.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import com.deer.backup.vo.RemoteVo;

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.connection.channel.direct.Session.Command;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import net.schmizz.sshj.xfer.FileSystemFile;

public class SshjUtils {

	// 创建连接
	public static SSHClient getConnect(RemoteVo remote) throws IOException {
		SSHClient sshClient = new SSHClient();
		sshClient.addHostKeyVerifier(new PromiscuousVerifier());
		sshClient.connect(remote.getHost(), remote.getPort());
		sshClient.authPassword(remote.getUser(), remote.getPassword());
		return sshClient;
	}

	// 关闭连接
	public void closeConnect(SSHClient sshClient) throws Exception {
		sshClient.disconnect();
	}

	// 执行命令
	public static List<String> remoteExecute(SSHClient sshClient, String command) throws Exception {
		List<String> resultLines = new ArrayList<>();
		Session session = sshClient.startSession();
		Command cmd = session.exec(command);
		InputStream input = cmd.getInputStream();
		if (input != null) {
			BufferedReader inputReader = new BufferedReader(new InputStreamReader(input));
			String inputLine = null;
			while ((inputLine = inputReader.readLine()) != null) {
				resultLines.add(inputLine);
			}
			input.close();
			session.close();
		}
		return resultLines;
	}

	// SFTP上传文件
	public static void sftpTo(SSHClient sshClient, String source, String destination) throws Exception {
		SFTPClient sftp = sshClient.newSFTPClient();
		sftp.put(new FileSystemFile(source), destination);
	}

	// SFTP下载文件
	public static void sftpDownload(SSHClient sshClient, String source, String destination) throws Exception {
		SFTPClient sftp = sshClient.newSFTPClient();
		sftp.get(source, destination);
	}
}
